package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConstantProperties props;
    @Override
    public String imageUpload(MultipartFile file) {
        try {
            //1.业务校验验证文件是否为图片，借助ImageIO读取图片。继续判断图片文件后缀名是否符合要求，图片长宽

            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new GuiguException(400, "图片格式非法！");
            }
            //2.调用MInIO-Java客户端对象将文件上传到MInIO-文件上传
            //2.1 动态生成上传文件名称 /当日日期/UUID.后缀
            String folderName = "/" + DateUtil.today() + "/";
            String fileName = IdUtil.randomUUID();
            String extName = FileUtil.extName(file.getOriginalFilename());  //
            String objectName = folderName + fileName + "." + extName;
            minioClient.putObject(PutObjectArgs.builder()
                    .object(objectName)
                    .bucket(props.getBucketName())
//                    .bucket(props.getBucketName())
                    .contentType("sph")
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build());

            return props.getEndpointUrl()+"/"+props.getBucketName()+objectName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
